/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.jfonia.notation;

import org.jfonia.connect5.basics.MutableValueNode;
import org.jfonia.connect5.basics.Observer;
import org.jfonia.connect5.intervals.BasicIntInterval;
import org.jfonia.model.elements.MusicalElement;
import org.jfonia.model.elements.Tone;

/**
 *
 * @author Rik Bauwens
 */
public class ObservableRest extends ObservableNoteOrRest
{
        private Rest rest;

        public ObservableRest(StaffElementSequence parentSequence,
                              Tone tone, BasicIntInterval noteLength)
        {
                super(parentSequence, tone, noteLength);
                requestLock();
                //Initialise nodes
                rest = MusicalTime.toRest(tone.getDifference());
                //Initialise observers
                init();
                removeLock();
        }

        private void init()
        {
                tone.getDifferenceNode().addObserver(new Observer()
                {
                        public void onNotify(Object source)
                        {
                                if(!requestLock())
                                        return;
                                setRest(MusicalTime.toRest(((MutableValueNode<Integer>) source).getValue()));
                                removeLock();
                        }
                });
                rest.getRestNode().addObserver(new Observer()
                {
                        public void onNotify(Object source)
                        {
                                setMusicalTime(rest);
                        }
                });
                rest.getDotsNode().addObserver(new Observer()
                {
                        public void onNotify(Object source)
                        {
                                setMusicalTime(rest);
                        }
                });
        }

        private void setRest(Rest rest)
        {
                this.rest.setRest(rest.getRest());
                this.rest.setDots(rest.getDots());
        }

        public Rest getRest()
        {
                return rest;
        }

        public MutableValueNode<Integer> getRestNode()
        {
                return rest.getRestNode();
        }

        public MutableValueNode<Integer> getDotsNode()
        {
                return rest.getDotsNode();
        }

        @Override
        public MusicalElement clone()
        {
                BasicIntInterval interval = new BasicIntInterval();
                interval.setBegin(noteLength.getBegin());
                interval.setDifference(noteLength.getDifference());
                return new ObservableRest(parentSequence, tone.clone(), interval);
        }
}
